from flask import Flask, request, jsonify
from flask_cors import CORS
from openai import OpenAI

import json
from sys import displayhook
import os

def show_json(obj):
    displayhook(json.loads(obj.model_dump_json()))

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())  # 读取本地 .env 文件，里面定义了 OPENAI_API_KEY

print('OPENAI_BASE_URL:{}'.format(os.getenv("OPENAI_BASE_URL")))
print('OPENAI_API_KEY:{}'.format(os.getenv("OPENAI_API_KEY")))

# 配置 OpenAI 服务

client = OpenAI(
    # defaults to os.environ.get("OPENAI_API_KEY")
    api_key=os.getenv("OPENAI_API_KEY"),
    base_url=os.getenv("OPENAI_BASE_URL")
)

app = Flask(__name__)
CORS(app)

# Configure your OpenAI API key


@app.route('/chat', methods=['POST'])
def chat():
    data = request.json
    user_message = data.get('message')
    
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "user", "content": user_message}
        ],
    )
    print('response.choices[0]:{}'.format(response.choices[0].message.content))
    return jsonify({'response': response.choices[0].message.content})

if __name__ == '__main__':
    app.run(debug=True)
